package com.windea.study.kotlin.jvm.spam

import org.apache.http.config.*
import org.apache.http.conn.socket.*
import org.apache.http.conn.ssl.*
import org.apache.http.impl.client.*
import org.apache.http.impl.conn.*
import java.security.*
import java.security.cert.*
import javax.net.ssl.*

fun sslHttpClientBuild(): CloseableHttpClient {
	val socketFactoryRegistry = RegistryBuilder.create<ConnectionSocketFactory>()
		.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()!!)
		.build()
	//创建ConnectionManager，添加Connection配置信息
	val connectionManager = PoolingHttpClientConnectionManager(
		socketFactoryRegistry)
	return HttpClients.custom().setConnectionManager(connectionManager).build()
}

private fun trustAllHttpsCertificates(): SSLConnectionSocketFactory? {
	var socketFactory: SSLConnectionSocketFactory? = null
	val trustAllCerts = arrayOfNulls<TrustManager>(1)
	val tm = CustomTrustManager()
	trustAllCerts[0] = tm
	val sc: SSLContext?
	try {
		sc = SSLContext.getInstance("TLS")//sc = SSLContext.getInstance("TLS")
		sc!!.init(null, trustAllCerts, null)
		socketFactory = SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE)
		//HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	} catch(e: NoSuchAlgorithmException) {
		e.printStackTrace()
	} catch(e: KeyManagementException) {
		e.printStackTrace()
	}
	
	return socketFactory
}


class CustomTrustManager : TrustManager, X509TrustManager {
	override fun getAcceptedIssuers(): Array<X509Certificate>? {
		return null
	}
	
	override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) {
		//don't check
	}
	
	override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) {
		//don't check
	}
}
